package com.chen.palmar.project.init;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chen.palmar.R;
import com.chen.palmar.base.BaseFragment;
import com.chen.palmar.common.datasource.DataCenter;
import com.chen.palmar.common.override.BannerImageLoader;
import com.chen.palmar.common.override.HttpSubscriber;
import com.chen.palmar.common.widget.view.AutoTabLayout;
import com.chen.palmar.entity.HomeBanEntity;
import com.chen.palmar.entity.NewListEntity;
import com.chen.palmar.entity.ShopListEntity;
import com.chen.palmar.entity.TypeListEntity;
import com.chen.palmar.project.producer.ProducerDetailActivity;
import com.chen.palmar.project.producer.ProducerTypeActivity;
import com.chen.palmar.project.producer.StoreDetailActivity;
import com.orhanobut.logger.Logger;
import com.primb.androidlibs.ui.recyclerview.BaseQuickAdapter;
import com.primb.androidlibs.ui.recyclerview.BaseViewHolder;
import com.squareup.picasso.Picasso;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.zhy.autolayout.AutoLinearLayout;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import rx.Subscription;

/**
 * @author Chen
 * @date 2017/12/28
 * 功能描述：厂家
 */

public class ProducerFragment extends BaseFragment {

    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.banner_view)
    Banner bannerView;
    @Bind(R.id.rv_new_info)
    RecyclerView rvNewInfo;
    @Bind(R.id.rv_show_info)
    RecyclerView rvShowInfo;
    @Bind(R.id.scroll_producer)
    ScrollView scrollProducer;
    @Bind(R.id.swipe_producer)
    SwipeRefreshLayout swipeProducer;
    @Bind(R.id.rv_type_info)
    RecyclerView rvTypeInfo;
    @Bind(R.id.tab_detail)
    AutoTabLayout tabDetail;
    @Bind(R.id.loading_progress)
    ProgressBar loadingProgress;
    @Bind(R.id.tv_producer_no_data)
    TextView tvProducerNoData;
    private List<Object> images = new ArrayList<>();
    private BaseQuickAdapter<NewListEntity.DataBean, BaseViewHolder> adapter;
    private BaseQuickAdapter<ShopListEntity.DataBean, BaseViewHolder> adapterShop;
    private BaseQuickAdapter<TypeListEntity.DataBean, BaseViewHolder> adapterType;
    private Handler mHandler = new Handler();
    private boolean isFirst = true;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initData();
    }

    @Override
    public int getLayoutId() {
        return R.layout.fragment_producer;
    }

    @Override
    public void initData() {
        int statusBarHeight = -1;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            //获取status_bar_height资源的ID
            int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
            if (resourceId > 0) {
                //根据资源ID获取响应的尺寸值
                statusBarHeight = getResources().getDimensionPixelSize(resourceId);
                Logger.v(statusBarHeight + "---");
                ViewGroup.LayoutParams params = tvTitle.getLayoutParams();
                AutoLinearLayout.LayoutParams layoutParams = new AutoLinearLayout.LayoutParams(AutoLinearLayout.LayoutParams.MATCH_PARENT, AutoLinearLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(30, statusBarHeight + 25, 30, 25);
                tvTitle.setLayoutParams(layoutParams);
            }
        }
        swipeProducer.setOnRefreshListener(() -> {
            try {
                isFirst = true;
                getDataForWeb();
            } catch (Exception e) {
                e.printStackTrace();
                showToast("服务器数据格式异常");
                swipeProducer.setRefreshing(false);
            }
        });
        swipeProducer.setRefreshing(true);
        swipeProducer.setColorSchemeColors(ContextCompat.getColor(getContext(), android.R.color.holo_blue_bright), ContextCompat.getColor(getContext(), android.R.color.holo_green_light), ContextCompat.getColor(getContext(), android.R.color.holo_orange_light), ContextCompat.getColor(getContext(), android.R.color.holo_red_light));


        //设置指示器位置（当banner模式中有指示器时）
        bannerView.setIndicatorGravity(BannerConfig.CENTER);
        bannerView.setImageLoader(new BannerImageLoader());

        rvNewInfo.setNestedScrollingEnabled(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        rvNewInfo.setLayoutManager(linearLayoutManager);
        rvNewInfo.setItemAnimator(new DefaultItemAnimator());
        adapter = new BaseQuickAdapter<NewListEntity.DataBean, BaseViewHolder>(R.layout.item_producer_new) {
            @Override
            protected void convert(BaseViewHolder helper, NewListEntity.DataBean item) {
                helper.setText(R.id.tv_item_new_name, item.getTitle());
                helper.setText(R.id.tv_item_new_price, item.getGuidance_price() + "元");
                ImageView view = (ImageView) helper.getView(R.id.iv_item_new);
                Glide.with(getContext()).load(item.getImg()).placeholder(R.mipmap.occupy_icon).error(R.mipmap.occupy_icon).fitCenter().into(view);
            }
        };
        adapter.setOnItemClickListener((adapter1, view, position) -> {
            Intent intent = new Intent(getContext(), StoreDetailActivity.class);
            intent.putExtra("info", adapter.getData().get(position).getProductId() + "");
            startActivity(intent);
        });
        rvNewInfo.setAdapter(adapter);


        rvShowInfo.setNestedScrollingEnabled(false);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getContext(), 3);
        gridLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvShowInfo.setLayoutManager(gridLayoutManager);
        rvShowInfo.setItemAnimator(new DefaultItemAnimator());
        adapterShop = new BaseQuickAdapter<ShopListEntity.DataBean, BaseViewHolder>(R.layout.item_producer_shop) {
            @Override
            protected void convert(BaseViewHolder helper, ShopListEntity.DataBean item) {
                helper.setText(R.id.tv_item_shop_name, item.getName());
                ImageView view = (ImageView) helper.getView(R.id.iv_item_shop);
                Picasso.with(getContext()).load(item.getLogo()).placeholder(R.mipmap.occupy_icon).error(R.mipmap.occupy_icon).fit().into(view);
            }
        };
        adapterShop.setOnItemClickListener((adapter1, view, position) -> {
            Intent intent = new Intent(getContext(), ProducerDetailActivity.class);
            intent.putExtra("info", adapterShop.getData().get(position).getFactoryId() + "");
            startActivity(intent);
        });
        rvShowInfo.setAdapter(adapterShop);

        rvTypeInfo.setNestedScrollingEnabled(false);
        GridLayoutManager typeLayoutManager = new GridLayoutManager(getContext(), 5);
        typeLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvTypeInfo.setLayoutManager(typeLayoutManager);
        rvTypeInfo.setItemAnimator(new DefaultItemAnimator());
        adapterType = new BaseQuickAdapter<TypeListEntity.DataBean, BaseViewHolder>(R.layout.item_producer_type) {
            @Override
            protected void convert(BaseViewHolder helper, TypeListEntity.DataBean item) {
                helper.setText(R.id.tv_item_type_name, item.getName());
                ImageView view = (ImageView) helper.getView(R.id.iv_item_type);
                Picasso.with(getContext()).load(item.getImg()).into(view);
            }
        };
        adapterType.setOnItemClickListener((adapter1, view, position) -> {
            Intent intent = new Intent(getContext(), ProducerTypeActivity.class);
            intent.putExtra("info", adapterType.getData().get(position).getCategoryId() + "");
            intent.putExtra("index", position);
            intent.putExtra("list", (Serializable) adapterType.getData());
            startActivity(intent);
        });
        rvTypeInfo.setAdapter(adapterType);

        bannerView.setOnBannerListener(position -> {
            if (images.size() > 0) {
                HomeBanEntity.DataBean dataBean = (HomeBanEntity.DataBean) images.get(position);
                Intent intent = new Intent(getContext(), ProducerDetailActivity.class);
                intent.putExtra("info", dataBean.getRef_id() + "");
                startActivity(intent);
            }
        });

        tabDetail.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int tag = (int) tab.getTag();
                try {
                    getShopData(tag, !isFirst);
                } catch (Exception e) {
                    e.printStackTrace();
                    showToast("服务器数据格式异常");
                    swipeProducer.setRefreshing(false);
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });


        try {
            getDataForWeb();
        } catch (Exception e) {
            e.printStackTrace();
            showToast("服务器数据格式异常");
            swipeProducer.setRefreshing(false);
        }
    }

    private void getShopData(int tag, boolean isScroll) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("categoryId", tag);
        Subscription subscribeShop = DataCenter.listProducerShop(map).subscribe(new HttpSubscriber<ShopListEntity>(getContext(), null) {
            @Override
            public void onNext(ShopListEntity listEntity) {
                isFirst = false;
                adapterShop.setNewData(listEntity.getData());
                swipeProducer.setRefreshing(false);
                loadingProgress.setVisibility(View.GONE);
                tvProducerNoData.setVisibility(View.GONE);
                if (listEntity.getData().size() <= 0) {
                    tvProducerNoData.setVisibility(View.VISIBLE);
                    tvProducerNoData.setText("该分类暂无店铺");
                }

                if (isScroll) {
                    mHandler.postDelayed(() -> {
                        int top = scrollProducer.getBottom();
                        scrollProducer.smoothScrollTo(0, top);
                    }, 300);
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                isFirst = false;
                swipeProducer.setRefreshing(false);
                loadingProgress.setVisibility(View.GONE);
                tvProducerNoData.setVisibility(View.VISIBLE);
                tvProducerNoData.setText("分类数据加载失败，请刷新");
            }
        });
        subscription.add(subscribeShop);
    }

    private void getDataForWeb() throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        Subscription subscribe = DataCenter.listProducerNew(map).subscribe(new HttpSubscriber<NewListEntity>(getContext(), null) {
            @Override
            public void onNext(NewListEntity listEntity) {
                adapter.setNewData(listEntity.getData());
                swipeProducer.setRefreshing(false);
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                swipeProducer.setRefreshing(false);
            }
        });
        subscription.add(subscribe);

        Subscription subscribeType = DataCenter.listProducerType(map).subscribe(new HttpSubscriber<TypeListEntity>(getContext(), null) {

            @Override
            public void onNext(TypeListEntity listEntity) {
                adapterType.setNewData(listEntity.getData());
                swipeProducer.setRefreshing(false);

                tabDetail.setVisibility(View.VISIBLE);
                loadingProgress.setVisibility(View.VISIBLE);
                rvShowInfo.setVisibility(View.VISIBLE);
                tvProducerNoData.setVisibility(View.GONE);

                for (int i = 0; i < listEntity.getData().size(); i++) {
                    TabLayout.Tab tab = tabDetail.newTab();
                    tab.setTag(listEntity.getData().get(i).getCategoryId());
                    tab.setText(listEntity.getData().get(i).getName());
                    if (0 == i) {
                        tabDetail.addTab(tab, true);
                    } else {
                        tabDetail.addTab(tab);
                    }
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                tabDetail.setVisibility(View.GONE);
                loadingProgress.setVisibility(View.GONE);
                swipeProducer.setRefreshing(false);
                tvProducerNoData.setVisibility(View.VISIBLE);
                tvProducerNoData.setText("分类数据加载失败，请刷新");
            }
        });
        subscription.add(subscribeType);

        HashMap<String, String> mapBan = new HashMap<>();
        mapBan.put("type", "1");
        mapBan.put("position", "3");
        Subscription banSub = DataCenter.homeBanInfo(mapBan).subscribe(new HttpSubscriber<HomeBanEntity>(getContext(), null) {
            @Override
            public void onNext(HomeBanEntity homeEntity) {
                images.clear();
                images.addAll(homeEntity.getData());
                bannerView.setImages(images);
                bannerView.start();
            }
        });
        subscription.add(banSub);
    }

    @OnClick({R.id.tv_shop_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_shop_more:
                if (adapterType.getData().size() > 0) {
                    Intent intent = new Intent(getContext(), ProducerTypeActivity.class);
                    intent.putExtra("info", adapterType.getData().get(0).getCategoryId() + "");
                    intent.putExtra("index", 0);
                    intent.putExtra("list", (Serializable) adapterType.getData());
                    startActivity(intent);
                } else {
                    showToast("服务器数据为空");
                }
                break;
        }
    }
}
